<template>
  <div class="notifications-page">
    <div class="page-header">
      <div class="header-left">
        <h1 class="page-title">通知中心</h1>
        <p class="page-subtitle">系统通知与消息管理</p>
      </div>
      <div class="header-right">
        <a-space>
          <a-badge :count="unreadCount" :offset="[-5, 5]">
            <a-button @click="markAllAsRead">
              <CheckOutlined /> 全部标为已读
            </a-button>
          </a-badge>
          <a-button @click="loadNotifications">
            <ReloadOutlined /> 刷新
          </a-button>
        </a-space>
      </div>
    </div>

    <div class="notifications-content">
      <a-row :gutter="24">
        <a-col :span="6">
          <a-card :bordered="false" class="filter-card">
            <div class="filter-section">
              <h3 class="filter-title">筛选</h3>

              <div class="filter-group">
                <div class="filter-label">类型</div>
                <a-checkbox-group v-model:value="filters.types" @change="loadNotifications">
                  <div class="filter-option">
                    <a-checkbox value="alert">告警通知</a-checkbox>
                  </div>
                  <div class="filter-option">
                    <a-checkbox value="ticket">工单通知</a-checkbox>
                  </div>
                  <div class="filter-option">
                    <a-checkbox value="system">系统通知</a-checkbox>
                  </div>
                  <div class="filter-option">
                    <a-checkbox value="user">用户通知</a-checkbox>
                  </div>
                </a-checkbox-group>
              </div>

              <a-divider />

              <div class="filter-group">
                <div class="filter-label">状态</div>
                <a-radio-group v-model:value="filters.status" @change="loadNotifications">
                  <div class="filter-option">
                    <a-radio value="all">全部</a-radio>
                  </div>
                  <div class="filter-option">
                    <a-radio value="unread">未读</a-radio>
                  </div>
                  <div class="filter-option">
                    <a-radio value="read">已读</a-radio>
                  </div>
                </a-radio-group>
              </div>

              <a-divider />

              <div class="filter-group">
                <div class="filter-label">优先级</div>
                <a-checkbox-group v-model:value="filters.priorities" @change="loadNotifications">
                  <div class="filter-option">
                    <a-checkbox value="critical">
                      <a-badge status="error" text="紧急" />
                    </a-checkbox>
                  </div>
                  <div class="filter-option">
                    <a-checkbox value="high">
                      <a-badge status="warning" text="高" />
                    </a-checkbox>
                  </div>
                  <div class="filter-option">
                    <a-checkbox value="medium">
                      <a-badge status="processing" text="中" />
                    </a-checkbox>
                  </div>
                  <div class="filter-option">
                    <a-checkbox value="low">
                      <a-badge status="default" text="低" />
                    </a-checkbox>
                  </div>
                </a-checkbox-group>
              </div>
            </div>
          </a-card>
        </a-col>

        <a-col :span="18">
          <a-card :bordered="false" :loading="loading">
            <a-list
              :data-source="notifications"
              :pagination="pagination"
              item-layout="horizontal"
            >
              <template #renderItem="{ item }">
                <a-list-item
                  :class="['notification-item', { unread: !item.read }]"
                  @click="handleNotificationClick(item)"
                >
                  <a-list-item-meta>
                    <template #avatar>
                      <a-badge :dot="!item.read">
                        <a-avatar :style="{ backgroundColor: getNotificationColor(item.type) }">
                          <component :is="getNotificationIcon(item.type)" />
                        </a-avatar>
                      </a-badge>
                    </template>
                    <template #title>
                      <div class="notification-title">
                        <span class="title-text">{{ item.title }}</span>
                        <a-tag :color="getPriorityColor(item.priority)" size="small">
                          {{ getPriorityLabel(item.priority) }}
                        </a-tag>
                      </div>
                    </template>
                    <template #description>
                      <div class="notification-description">
                        {{ item.content }}
                      </div>
                      <div class="notification-meta">
                        <a-space :size="16">
                          <span>
                            <ClockCircleOutlined />
                            {{ formatTime(item.createdAt) }}
                          </span>
                          <a-tag :bordered="false">
                            {{ getTypeLabel(item.type) }}
                          </a-tag>
                        </a-space>
                      </div>
                    </template>
                  </a-list-item-meta>
                  <template #actions>
                    <a-space>
                      <a-button
                        v-if="!item.read"
                        type="link"
                        size="small"
                        @click.stop="markAsRead(item)"
                      >
                        标为已读
                      </a-button>
                      <a-button
                        type="link"
                        size="small"
                        danger
                        @click.stop="deleteNotification(item)"
                      >
                        删除
                      </a-button>
                    </a-space>
                  </template>
                </a-list-item>
              </template>
            </a-list>

            <a-empty v-if="notifications.length === 0" description="暂无通知" />
          </a-card>
        </a-col>
      </a-row>
    </div>

    <!-- Notification Detail Modal -->
    <a-modal
      v-model:open="detailModalVisible"
      :title="selectedNotification?.title"
      :footer="null"
      width="700px"
    >
      <div v-if="selectedNotification" class="notification-detail">
        <div class="detail-header">
          <a-space>
            <a-tag :color="getPriorityColor(selectedNotification.priority)">
              {{ getPriorityLabel(selectedNotification.priority) }}
            </a-tag>
            <a-tag :bordered="false">
              {{ getTypeLabel(selectedNotification.type) }}
            </a-tag>
          </a-space>
          <div class="detail-time">
            <ClockCircleOutlined />
            {{ formatTime(selectedNotification.createdAt) }}
          </div>
        </div>

        <a-divider />

        <div class="detail-content">
          {{ selectedNotification.content }}
        </div>

        <div v-if="selectedNotification.metadata" class="detail-metadata">
          <a-divider />
          <h4>相关信息</h4>
          <a-descriptions :column="1" size="small">
            <a-descriptions-item
              v-for="(value, key) in selectedNotification.metadata"
              :key="key"
              :label="key"
            >
              {{ value }}
            </a-descriptions-item>
          </a-descriptions>
        </div>

        <div class="detail-actions">
          <a-divider />
          <a-space>
            <a-button
              v-if="!selectedNotification.read"
              type="primary"
              @click="markAsRead(selectedNotification)"
            >
              标为已读
            </a-button>
            <a-button @click="detailModalVisible = false">关闭</a-button>
          </a-space>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import {
  BellOutlined,
  CheckOutlined,
  ReloadOutlined,
  ClockCircleOutlined,
  AlertOutlined,
  FileTextOutlined,
  SettingOutlined,
  UserOutlined,
} from '@ant-design/icons-vue'
import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'
import 'dayjs/locale/zh-cn'

dayjs.extend(relativeTime)
dayjs.locale('zh-cn')

interface Notification {
  _id: string
  type: 'alert' | 'ticket' | 'system' | 'user'
  priority: 'critical' | 'high' | 'medium' | 'low'
  title: string
  content: string
  read: boolean
  createdAt: string
  metadata?: Record<string, any>
}

const loading = ref(false)
const notifications = ref<Notification[]>([])
const detailModalVisible = ref(false)
const selectedNotification = ref<Notification | null>(null)

const filters = reactive({
  types: ['alert', 'ticket', 'system', 'user'],
  status: 'all',
  priorities: ['critical', 'high', 'medium', 'low'],
})

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条`,
  onChange: (page: number, pageSize: number) => {
    pagination.current = page
    pagination.pageSize = pageSize
    loadNotifications()
  },
})

const unreadCount = computed(() => {
  return notifications.value.filter(n => !n.read).length
})

const loadNotifications = async () => {
  try {
    loading.value = true

    // TODO: Replace with actual API call when backend is ready
    // For now, using mock data
    const mockNotifications: Notification[] = [
      {
        _id: '1',
        type: 'alert',
        priority: 'critical',
        title: '生产环境CPU使用率超过90%',
        content: '服务器 prod-server-01 的CPU使用率持续超过90%，请尽快处理',
        read: false,
        createdAt: new Date(Date.now() - 300000).toISOString(),
        metadata: {
          服务器: 'prod-server-01',
          CPU使用率: '92%',
          持续时间: '5分钟',
        },
      },
      {
        _id: '2',
        type: 'ticket',
        priority: 'high',
        title: '工单 #1234 已分配给您',
        content: '您有一个新的高优先级工单需要处理',
        read: false,
        createdAt: new Date(Date.now() - 3600000).toISOString(),
        metadata: {
          工单编号: '#1234',
          优先级: '高',
          类型: '故障',
        },
      },
      {
        _id: '3',
        type: 'system',
        priority: 'medium',
        title: '系统维护通知',
        content: '系统将于今晚23:00-01:00进行维护升级',
        read: true,
        createdAt: new Date(Date.now() - 7200000).toISOString(),
      },
      {
        _id: '4',
        type: 'user',
        priority: 'low',
        title: '密码即将过期',
        content: '您的密码将在7天后过期，请及时修改',
        read: true,
        createdAt: new Date(Date.now() - 86400000).toISOString(),
      },
    ]

    // Apply filters
    let filtered = mockNotifications.filter(n => {
      if (!filters.types.includes(n.type)) return false
      if (!filters.priorities.includes(n.priority)) return false
      if (filters.status === 'read' && !n.read) return false
      if (filters.status === 'unread' && n.read) return false
      return true
    })

    notifications.value = filtered
    pagination.total = filtered.length
  } catch (error) {
    console.error('Failed to load notifications:', error)
    message.error('加载通知失败')
  } finally {
    loading.value = false
  }
}

const handleNotificationClick = (notification: Notification) => {
  selectedNotification.value = notification
  detailModalVisible.value = true
  if (!notification.read) {
    markAsRead(notification)
  }
}

const markAsRead = async (notification: Notification) => {
  try {
    // TODO: Replace with actual API call
    console.log('Mark as read:', notification._id)
    notification.read = true
    message.success('已标为已读')
  } catch (error) {
    console.error('Failed to mark as read:', error)
    message.error('操作失败')
  }
}

const markAllAsRead = async () => {
  try {
    // TODO: Replace with actual API call
    console.log('Mark all as read')
    notifications.value.forEach(n => {
      n.read = true
    })
    message.success('全部已标为已读')
  } catch (error) {
    console.error('Failed to mark all as read:', error)
    message.error('操作失败')
  }
}

const deleteNotification = async (notification: Notification) => {
  try {
    // TODO: Replace with actual API call
    console.log('Delete notification:', notification._id)
    const index = notifications.value.findIndex(n => n._id === notification._id)
    if (index > -1) {
      notifications.value.splice(index, 1)
    }
    message.success('通知已删除')
  } catch (error) {
    console.error('Failed to delete notification:', error)
    message.error('删除失败')
  }
}

const getNotificationIcon = (type: string) => {
  const icons: Record<string, any> = {
    alert: AlertOutlined,
    ticket: FileTextOutlined,
    system: SettingOutlined,
    user: UserOutlined,
  }
  return icons[type] || BellOutlined
}

const getNotificationColor = (type: string): string => {
  const colors: Record<string, string> = {
    alert: '#f5222d',
    ticket: '#1890ff',
    system: '#52c41a',
    user: '#722ed1',
  }
  return colors[type] || '#666'
}

const getPriorityColor = (priority: string): string => {
  const colors: Record<string, string> = {
    critical: 'error',
    high: 'warning',
    medium: 'processing',
    low: 'default',
  }
  return colors[priority] || 'default'
}

const getPriorityLabel = (priority: string): string => {
  const labels: Record<string, string> = {
    critical: '紧急',
    high: '高',
    medium: '中',
    low: '低',
  }
  return labels[priority] || priority
}

const getTypeLabel = (type: string): string => {
  const labels: Record<string, string> = {
    alert: '告警通知',
    ticket: '工单通知',
    system: '系统通知',
    user: '用户通知',
  }
  return labels[type] || type
}

const formatTime = (time: string): string => {
  return dayjs(time).fromNow()
}

onMounted(() => {
  loadNotifications()
})
</script>

<style scoped lang="scss">
.notifications-page {
  height: 100%;
  overflow: auto;
  background: #f5f5f5;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  padding: 24px;
  border-bottom: 1px solid #f0f0f0;

  .page-title {
    margin: 0;
    font-size: 24px;
    font-weight: 600;
  }

  .page-subtitle {
    margin: 4px 0 0;
    color: #8c8c8c;
    font-size: 14px;
  }
}

.notifications-content {
  padding: 24px;
}

.filter-card {
  .filter-section {
    .filter-title {
      margin: 0 0 16px;
      font-size: 16px;
      font-weight: 600;
    }

    .filter-group {
      margin-bottom: 16px;

      .filter-label {
        margin-bottom: 12px;
        font-weight: 500;
        color: #262626;
      }

      .filter-option {
        padding: 6px 0;
      }
    }
  }
}

.notification-item {
  cursor: pointer;
  transition: all 0.3s;
  padding: 16px;
  border-radius: 4px;

  &.unread {
    background-color: #f0f5ff;
  }

  &:hover {
    background-color: #fafafa;
  }

  .notification-title {
    display: flex;
    align-items: center;
    gap: 8px;

    .title-text {
      font-weight: 500;
    }
  }

  .notification-description {
    margin: 8px 0;
    color: #595959;
  }

  .notification-meta {
    margin-top: 8px;
    font-size: 12px;
    color: #8c8c8c;
  }
}

.notification-detail {
  .detail-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .detail-time {
      color: #8c8c8c;
      font-size: 14px;
    }
  }

  .detail-content {
    margin: 16px 0;
    line-height: 1.6;
    color: #262626;
  }

  .detail-metadata {
    margin-top: 16px;

    h4 {
      margin-bottom: 12px;
      font-size: 14px;
      font-weight: 600;
    }
  }

  .detail-actions {
    margin-top: 16px;
  }
}
</style>
